package cn.wolfcode.service.impl;

import cn.wolfcode.domain.ActivityItem;
import cn.wolfcode.domain.Employee;
import cn.wolfcode.mapper.ActivityItemMapper;
import cn.wolfcode.qo.QueryObject;
import cn.wolfcode.service.IActivityItemService;
import cn.wolfcode.util.UserContext;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

@Service
@Transactional
public class ActivityItemServiceImpl implements IActivityItemService {

    @Autowired
    private ActivityItemMapper activityItemMapper;



    @Override
    public void save(ActivityItem activityItem) {
        activityItemMapper.insert(activityItem);
    }

    @Override
    public void delete(Long id) {
        activityItemMapper.deleteByPrimaryKey(id);
    }

    @Override
    public void update(ActivityItem activityItem) {
        activityItemMapper.updateByPrimaryKey(activityItem);
    }

    @Override
    public ActivityItem get(Long id) {
        return activityItemMapper.selectByPrimaryKey(id);
    }

    @Override
    public List<ActivityItem> listAll() {
        return activityItemMapper.selectAll();
    }

    @Override
    public PageInfo<ActivityItem> query(QueryObject qo) {
        PageHelper.startPage(qo.getCurrentPage(),qo.getPageSize()); //对下一句sql进行自动分页
        List<ActivityItem> activityItems = activityItemMapper.selectForList(qo); //里面不需要自己写limit
        return new PageInfo<ActivityItem>(activityItems);
    }

    @Override
    public List<ActivityItem> getByaId(Long aId) {
        List<ActivityItem> activityItem =   activityItemMapper.selectByaId(aId);
        return activityItem;
    }



    @Override
    public void updateData(Long id) {
        Employee user = UserContext.getCurrentUser();

            //            进行数量更新
            ActivityItem activityItem = activityItemMapper.selectByPrimaryKey(id);
            Integer num = activityItem.getNum();
            num += 1;
            activityItemMapper.updateNum(id,num);
            //       choice对应的数据,投票人,投票的明细,投票时间
            activityItemMapper.insertRelation(user.getId(),id,new Date());

    }

    @Override
    public Boolean  queryData(Long aId) {
        Employee user = UserContext.getCurrentUser();
//             根据aid查询出所有的ai id;
        List<ActivityItem> activityItems = activityItemMapper.selectByaId(aId);
//             通过员工id 去获取choice 中的 ai 表的 id
        List<Long> ids = activityItemMapper.selectInChoice(user.getId());
//        遍历所有

        for (ActivityItem a : activityItems){
            Long id = a.getId();
            if(ids.contains(id)){
                return false;
            }
        }
        return  true;
    }
}
